
package com.platform.modules.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.annotation.SysLog;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.controller.dto.MallCardShopsDto;
import com.platform.modules.mall.entity.MallCardShopsEntity;
import com.platform.modules.mall.entity.MallCardSnEntity;
import com.platform.modules.mall.entity.MallGoodsEntity;
import com.platform.modules.mall.service.IAssociTagDataChange;
import com.platform.modules.mall.service.MallCardShopsService;
import com.platform.modules.mall.service.MallCardSnService;
import com.platform.modules.mall.service.MallGoodsService;
import com.platform.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 商品表Controller
 *
 * @author
 * @date 2019-07-03 17:58:29
 */
@RestController
@RequestMapping("mall/goods")
public class MallGoodsController extends AbstractController {
    @Autowired
    private MallGoodsService mallGoodsService;
    @Autowired
    private MallCardShopsService mallCardShopsService;
    @Autowired
    private MallCardSnService snService;
//    @Resource
//    private MallAssociTagService associTagService;
    @Resource
    private IAssociTagDataChange shopsGoodsTag;

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAllSimple")
    @RequiresPermissions("mall:goods:list")
    public RestResponse queryAllSimple(@RequestParam Map<String, Object> params) {
        List<MallGoodsEntity> list = mallGoodsService.list(new LambdaQueryWrapper<MallGoodsEntity>()
                .select(MallGoodsEntity::getId, MallGoodsEntity::getName).eq(MallGoodsEntity::getType, params.get("type"))
                .eq(MallGoodsEntity::getIsOnSale, params.get("isOnSale")).like(MallGoodsEntity::getName, params.get("name")));

        return RestResponse.success().put("list", list);
    }

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("mall:goods:list")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {
        List<MallGoodsEntity> list = mallGoodsService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 分页查询商品表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("mall:goods:list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        Page page = mallGoodsService.queryPage(params);

        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mall:goods:info")
    public RestResponse info(@PathVariable("id") String id) {
        MallGoodsEntity mallGoods = mallGoodsService.queryById(id);

        return RestResponse.success().put("goods", mallGoods);
    }

    /**
     * 新增商品表
     *
     * @param mallGoods mallGoods
     * @return RestResponse
     */
    @SysLog("新增商品表")
    @RequestMapping("/save")
    @RequiresPermissions("mall:goods:save")
    public RestResponse save(@RequestBody MallGoodsEntity mallGoods) {

//        if(mallGoods.getGoodsType().equals(1) &&  StringUtils.isEmpty(mallGoods)){
//        }

        mallGoodsService.add(mallGoods);
        if (1 == mallGoods.getGoodsType() && mallGoods.getGoodsNumber() > 0) {
            return RestResponse.error("电子卡券请先保存后在修改库存");
        }

        return RestResponse.success();
    }

    /**
     * 实体验证
     *
     * @param entity
     * @return 返回错误消息
     */
    private String entityVerify(MallGoodsEntity entity) {
        // 判断卡券密钥库存
        Integer snNumber = snService.count(new QueryWrapper<MallCardSnEntity>().eq("goods_Id", entity.getId()).eq("status", "0"));
        if (entity.getGoodsType() == 1 && entity.getGoodsNumber() > snNumber) {
            return "库存不能大于卡券数量!" + String.format("\n当前卡券数量【%s】", snNumber);
        }
        return null;
    }

    /**
     * 修改商品表
     *
     * @param mallGoods mallGoods
     * @return RestResponse
     */
    @SysLog("修改商品表")
    @RequestMapping("/update")
    @RequiresPermissions("mall:goods:update")
    public RestResponse update(@RequestBody MallGoodsEntity mallGoods) {
        if (1 == mallGoods.getGoodsType()) {
            String errorMessage = entityVerify(mallGoods);
            if (!StringUtils.isNullOrEmpty(errorMessage)) {
                return RestResponse.error(errorMessage);
            }
        }

        MallGoodsEntity old = mallGoodsService.getById(mallGoods.getId());
        if(!old.getName().equals(mallGoods.getName())){
            shopsGoodsTag.update(old.getId(),mallGoods);
        }
        mallGoodsService.update(mallGoods);
        return RestResponse.success();
    }

    /**
     * 根据主键删除商品表
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除商品表")
    @RequestMapping("/delete")
    @RequiresPermissions("mall:goods:delete")
    public RestResponse delete(@RequestBody String[] ids) {
        mallGoodsService.deleteBatch(ids);
        // 删除标签
        shopsGoodsTag.delate(ids);
        return RestResponse.success();
    }

    /**
     * 商品上架、下架
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("商品上架、下架")
    @RequestMapping("/changeSale")
    @RequiresPermissions("mall:goods:changeSale")
    public RestResponse changeSale(@RequestBody String[] ids) {
        mallGoodsService.changeSale(ids);

        return RestResponse.success();
    }


    /**
     * 查看卡卷与店铺关联
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAllCardShops")
    @RequiresPermissions("mall:goods:list")
    public RestResponse queryAllCardShops(@RequestParam Map<String, Object> params) {
        if (StringUtils.isBlank((String) params.get("goodsId"))) {
            RestResponse.error("卡卷id为空");
        }
        List<MallCardShopsEntity> list = mallCardShopsService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 新增卡卷与店铺关联
     *
     * @param mallCardShopsDto mallCardShopsDtos
     * @return RestResponse
     */
    @SysLog("新增卡卷与店铺关联")
    @RequestMapping("/saveCardShops")
    @RequiresPermissions("mall:goods:save")
    @Transactional
    public RestResponse saveCardShops(@RequestBody MallCardShopsDto mallCardShopsDto) {
        mallCardShopsService.deleteByCardId(mallCardShopsDto.getGoodsId());
        List<MallCardShopsEntity> mallCardShopsEntities = new ArrayList<>();
        MallCardShopsEntity mallCardShopsEntity;
        for (String shopsId : mallCardShopsDto.getShopsIds()) {
            mallCardShopsEntity = new MallCardShopsEntity();
            mallCardShopsEntity.setGoodsId(mallCardShopsDto.getGoodsId());
            mallCardShopsEntity.setShopsId(shopsId);
            mallCardShopsEntities.add(mallCardShopsEntity);
        }
        mallCardShopsService.saveBatch(mallCardShopsEntities);

        return RestResponse.success();
    }
}
